package br.com.automed.validator;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import br.com.automed.util.Util;

@FacesValidator(value="com.automed.emailValidator")
public class EmailValidator implements Validator {

	public void validate(FacesContext context, UIComponent component, Object value)
			throws ValidatorException {
		
		Pattern patternBR = Pattern.compile("[a-zA-Z0-9\\._-]+@([a-zA-Z\\._-]+\\.)[a-zA-Z]{2}");
		Pattern patternCOM = Pattern.compile("[A-Za-z0-9\\._-]+@[A-Za-z]+\\.[A-Za-z]+");
		
		Matcher matcherBR = patternBR.matcher(value.toString());
		Matcher matcherCOM = patternCOM.matcher(value.toString());
		
		if(!matcherBR.matches() && !matcherCOM.matches()){
			
			FacesMessage message = new FacesMessage();
			message.setSummary(Util.getMessage("display.validator.email",null));
			message.setSeverity(FacesMessage.SEVERITY_WARN);
			
			throw new ValidatorException(message);
		}
		
	}

}
